import { Modal, Transfer } from 'antd';
import { useEffect, useState } from 'react';
import { PermissionItem } from '../../AuthPermission/data';
import { fetchConfigurableAuthPermissionV2, queryAdminRoleAccessList } from '../service';
import { Button } from 'antd/lib/radio';
import { UpdateRolePermissionBean } from '../data';

export interface AuthPermissionConfigurationProps {
  id: string;
  visible: boolean;
  onChange: (value: UpdateRolePermissionBean) => void;
  onCancel: (flag?: boolean) => void;
}
export default (props: AuthPermissionConfigurationProps) => {

  const {
    onChange: handleUpdate,
    onCancel: handleUpdateModalVisible,
    visible: updateModalVisible,
    id
  } = props;
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [items, setItems] = useState<any[]>();

  function transferAdminAccess2TransferItem(item: PermissionItem): any {
    return {
      key: item.id,
      title: item.name,
      description: item.name,
      disabled: false,
      ...item,
    };
  }

  useEffect(() => {

    // 加载已选择角色
    queryAdminRoleAccessList({ role_id: id }).then((res) => {
      const data = res.data?.flatMap((item) => transferAdminAccess2TransferItem(item)) || [];
      const fetchTargetKeys = data?.map((item) => `${item.key}` || '');
      setTargetKeys(fetchTargetKeys);
    });

    // 加载全部可选角色
    fetchConfigurableAuthPermissionV2({ role_id: id }).then((res) => {
      const data = res.data?.flatMap((item) => transferAdminAccess2TransferItem(item)) || [];
      setItems(data);
    });
    
  }, []);


  const handleChange = (targets: string[], _direction: string, _moveKeys: string[]) => {
    setTargetKeys(targets)
  };

  return (
    <Modal
      title="编辑权限"
      open={updateModalVisible}
      width={700}
      footer={null}
      centered
      onCancel={() => handleUpdateModalVisible(false)}
      afterClose={() => handleUpdateModalVisible(false)}
    >
      <Transfer
        showSearch
        dataSource={items}
        listStyle={{ height: '450px', width: '100%' }}
        titles={['可分配', '已分配']}
        targetKeys={targetKeys}
        onChange={handleChange}
        selectedKeys={selectedKeys}
        onSelectChange={(sourceSelectedKeys, targetSelectedKeys) => {
          setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys]);
        }}
        render={(item) => (item.title ? item.title : '')}
      />
      <Button onClick={
        () => handleUpdate({
          role_id: id,
          permission_ids: targetKeys
        })
      }>
        确定
      </Button>
    </Modal>

  );
};
